package common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

/**
 * Provides some utility methods used throughout the program.
 * 
 * @author Andrew Bernard
 */
public class Util {
    
  /**
   * Gets the first line from the stream after skipping the specified amount of lines
   * @param bis
   * @param linesToSkip
   */
  public static String getLineFromStream(BufferedReader bis, int linesToSkip) {
    String line = "";    
    try {
      for(int i = 0; i < linesToSkip; i++) bis.readLine();
      line = bis.readLine();
    } catch (Exception e) {
      System.err.println("There was an error reading the stream.");
    }
    return line;
  }
  
  /**
   * Returns the next char in an input stream. The stream marker will remain at it's
   * current position. This method relies on being able to use .mark() and .reset() 
   * so if mark is not supported the null primitive '\0' will be returned.
   * 
   * @param    reader    The input stream to read
   * @return    Next character in input stream
   * @throws    IOException
   */
  public static int peek(Reader reader) throws IOException {
    int nextChar = '\0';
    if(reader.markSupported()) {
      reader.mark(32);      
      nextChar = reader.read();
      reader.reset();
    }
    return nextChar;
  }
  
  /**
	 * Returns the next char in an input stream. The stream marker will remain at it's
   * current position. This method relies on being able to use .mark() and .reset() 
   * so if mark is not supported the null primitive '\0' will be returned.
   * 
	 * @param    stream    The input stream to read
	 * @return    Next character in input stream
	 * @throws    IOException
	 */
	public static int peek(InputStream stream) throws IOException {
		int nextChar = '\0';
		if(stream.markSupported()) {
      stream.mark(32);
		  nextChar = stream.read();
      stream.reset();
		}
	  return nextChar;
	}
  
  /**
   * Resizes a char array when necessary
   * @param    charArray    Char array to resize
   * @param    newSize    New size of array
   */
  public static char[] resizeCharArray(char[] charArray, int newSize) {
    char[] newCharArray = new char[newSize];
    for (int i = 0; i < charArray.length; i++) {
      newCharArray[i] = charArray[i];
    }
    return newCharArray;
  }
}
